from playwright.async_api import async_playwright
from config import *
from tool import tms
from myexcel import *
import requests,openpyxl,asyncio
import time,json,os,traceback

def get_group_list(group_name):

    '''获取浏览器指定分组列表'''
    session=requests.session()
    group_id=None
    api_group_url=f'{ADSPower_API_URL}/api/v1/group/list'
    for _ in range(3):
        parsms={
            'group_name':group_name
        }
        try:
            res=session.get(api_group_url,params=parsms)
            if res.status_code==200:
                json_data=res.json()
                if json_data['code']==0:
                    if json_data['data']['list']:
                        group_id=json_data['data']['list'][0]['group_id']
                        break
        except Exception as e:
            print(f'获取浏览器分组《{group_name}》信息错误=>{e}')
        
        time.sleep(3)
    
    if not group_id:
        return {'code':1,'msg':'获取分组信息错误','blist':None}

    
    api_url=f'{ADSPower_API_URL}/api/v2/browser-profile/list'
    page=1
    page_size=100
    blist=[]

    err_count=0
    while True:
        data={
            'group_id':group_id,
            'page':page,
            'limit':page_size
        }
        try:
            res=session.post(api_url,json=data)
            if res.status_code==200:

                json_data=res.json()
                if json_data['code']==0:
                    cur_blist=json_data['data']['list']
                    blist.extend(cur_blist)
                    print(f'第 {page} 页,一共 {len(cur_blist)} 个浏览器环境,当前总获取浏览器环境:{len(blist)} 个')
                    if len(cur_blist)<100:
                        
                        break
                    else:
                        page+=1
            
            else:
                err_count+=1
        
        except Exception as e:
            print(e)
            err_count+=1
        
        time.sleep(3)
        if err_count>10:
            return {'code':2,'msg':'错误超过三次','blist':None}
    
    return {'code':2,'msg':'请求成功','blist':blist}

def upload_dpinfo(group_name,gj='印尼',pt='Shopee'):
    '''上传群控店铺信息'''
    Platform_map={
        '印尼':"seller.shopee.co.id"
    }

    res=get_group_list(group_name)
    blist=res['blist']
    
    suc=0
    for binfo in blist:
        user_proxy_config=binfo['user_proxy_config']
        ProxyIP=None
        if user_proxy_config.get('proxy_host'):
            ptype,puser,pwd,phost,pport=user_proxy_config['proxy_type'],user_proxy_config['proxy_user'],user_proxy_config['proxy_password'],user_proxy_config['proxy_host'],user_proxy_config['proxy_port']
            ProxyIP=f"{ptype}://{puser}:{pwd}@{phost}:{pport}"
        bdata={
            'BrowserID':binfo['profile_id'],
            'DpName':binfo['name'],
            'GroupName':binfo['group_name'],
            'Platform':Platform_map.get(gj),
            'Country':gj,
            'PingTai':pt,
            'UserName':binfo['username'],
            'Password':binfo['password'],
            'ProxyIP':ProxyIP
        }

        zds=list(bdata.keys())
        paras=list(bdata.values())
        aff=tms.merge_into('HouTai',zds,paras,['BrowserID'])
        suc+=aff
        print(f"上传店铺:《{binfo['name']}》信息,状态:{aff}")
    print(f'共 {len(blist)} 个店铺,成功上传信息 {suc} 个')

def uoload_all_dpinfo():
    session=requests.session()
    api_url1=f'{ADSPower_API_URL}/api/v1/group/list'
    gs=[]
    for _ in range(3):
        parsms={
            'page':1,
            'page_size':2000

        }
        try:
            res=session.get(api_url1,params=parsms,timeout=60)
            if res.status_code==200:
                json_data=res.json()

                if json_data['code']==0:
                    if json_data['data']['list']:
                        gs=json_data['data']['list']
                        break
        except Exception as e:
            print(f'获取浏览器分组,信息错误=>{e}')
        
        time.sleep(3)
    print(f'当前共 {len(gs)} 个浏览器分组')
    for gj,ginfo in enumerate(gs,start=1):
        gid=ginfo['group_id']
        gname=ginfo['group_name']
        if gname in ['阿毛-泰国虾皮买家号','阿毛-菲律宾虾皮买家号','1688买家号 - 采集用','查找链接','1688买家号 - 采购用']:
            print(f'第 {gj} 个分组《{gname}》,gid:{gid},跳过上传')
            continue
        
        print(f'第 {gj} 个分组《{gname}》,gid:{gid},开始获取分组环境列表')
        api_url=f'{ADSPower_API_URL}/api/v2/browser-profile/list'
        page=1
        page_size=100
        blist=[]
        while True:
            data={
                'group_id':gid,
                'page':page,
                'limit':page_size
            }
            try:
                res=session.post(api_url,json=data)
                if res.status_code==200:

                    json_data=res.json()
                    if json_data['code']==0:
                        cur_blist=json_data['data']['list']
                        print(cur_blist)
                        exit()
                        blist.extend(cur_blist)
                        print(f'第 {page} 页,一共 {len(cur_blist)} 个浏览器环境,当前总获取浏览器环境:{len(blist)} 个')
                        if len(cur_blist)<100 or len(cur_blist)==0:
                            break
                        else:
                            page+=1
                else:
                    err_count+=1
            
            except Exception as e:
                print(e)
                err_count+=1
        print(f'第 {gj} 个分组《{gname}》,gid:{gid},共获取 {len(blist)}个列表')

        suc=0
        for binfo in blist:

            country='印尼'
            host='seller.shopee.co.id'
            price_times=2.2
            exchange_rate=2280
            is_KJ=0
            bname=binfo['name']
            if '泰国' in bname:
                country='泰国'
                host='seller.shopee.co.th'
                exchange_rate=4.58
            if '马来' in bname:
                country='马来西亚'
                host='seller.shopee.com.my'
                exchange_rate=0.60
            if '越南' in bname:
                host='banhang.shopee.vn'
                exchange_rate=3697
                country='越南'
            if '新加坡' in bname:
                exchange_rate=0.19
                country='新加坡'
            if '跨境' in bname or '3pf' in  bname:
                host='seller.shopee.cn'
                is_KJ=1
            
            user_proxy_config=binfo['user_proxy_config']
            ProxyIP=None
            if user_proxy_config.get('proxy_host'):
                ptype,puser,pwd,phost,pport=user_proxy_config['proxy_type'],user_proxy_config['proxy_user'],user_proxy_config['proxy_password'],user_proxy_config['proxy_host'],user_proxy_config['proxy_port']
                ProxyIP=f"{ptype}://{puser}:{pwd}@{phost}:{pport}"

            bdata={
                'BrowserID':binfo['profile_id'],
                'DpName':bname,
                'GroupName':binfo['group_name'],
                'Platform':host,
                'Country':country,
                'PingTai':'Shopee',
                'UserName':binfo['username'],
                'Password':binfo['password'],
                'ProxyIP':ProxyIP,
                'price_times':price_times,
                'exchange_rate':exchange_rate,
                'is_KJ':is_KJ
            }

            zds=list(bdata.keys())
            paras=list(bdata.values())
            aff=tms.merge_into('HouTai',zds,paras,['BrowserID'])
            suc+=aff
            print(f"上传店铺:《{binfo['name']}》信息,状态:{aff}")
        print(f'第 {gj} 个分组《{gname}》,gid:{gid},共存:{suc}')
        time.sleep(1)

def creare_tbl():

    tb_paths=os.listdir('TABLEJSON')
    for tb_path in tb_paths:
        tbname=tb_path.replace('.json','')
        if tb_path in ['caigoudan','ShopeeADCost','S1688SearchUrl','ShopeeKWReport','TABLE']:
            continue
        json_path=f'TABLEJSON/{tb_path}'
        with open(json_path,'r',encoding='utf-8') as f:
            en_to_cn=json.load(f)

        cols={}
        for col_name,cn_name in en_to_cn.items():
            if col_name.lower()=='id':
                dtype='[int] IDENTITY(1,1) primary key NOT NULL' 
            elif col_name.lower() in ['bid','shopid','browserid','shopid','dpname','groupname','gname']:
                dtype='nvarchar(100) null'
            elif col_name.lower() in ['bid','shopid','browserid','shopid','itemid','offerid','skuid']:
                dtype='nvarchar(20) null'

            elif col_name.lower() in ['update_time','upload_time']:
                dtype='[datetime] NULL'
            elif 'title' in col_name.lower():
                dtype='nvarchar(2000) null'
            elif ('pdec' in col_name.lower() 
                    or 'attributes' in col_name.lower() 
                    or '描述' in cn_name
                    or 'models' in col_name.lower()
                    or 'fe_categories' in col_name.lower()
                    or 'images' in col_name.lower()
                    or 'json_data' in col_name.lower()
                    or 'video_info_list' in col_name.lower()
                    or 'tier_variations' in col_name.lower()
                ):
                dtype='nvarchar(max) null'

            elif ('price' in col_name.lower()
                  or '(元)' in cn_name
                  or '销售额' in cn_name
                  ):
                dtype='DECIMAL(18,2)'
            

            elif cn_name.endswith('率') or col_name.lower().endswith('rate'):
                dtype='DECIMAL(18,4)'
            elif col_name.lower()=='random_code':
                dtype='nvarchar(8) null'

            elif '数' in cn_name or '数量' in cn_name or '量' in cn_name:
                dtype='int null'


            elif col_name.lower().startswith('is') or '是否' in cn_name:
                dtype='int default 0'
            
            else:
                dtype='nvarchar(500) null'
          
            cols[col_name]=dtype
        
        aff=tms.create_table(tbname,cols)
        print(f'创建表《{tbname}》,状态:{aff}')

def upload_task():

    tdatas=getDictDatasByEecel2('表格导出/Task()_2025-10-10_14-00-28.xlsx')
    
    tdata_name_map={}
    for tdata in tdatas[1:]:
        tdata_name_map[tdata['tName']]=tdata
    for ctid,ctname in Task_Name_dict.items():

        if tdata_name_map.get(ctname):
            pdata={
                'tName':ctname,
                'ShopClass':tdata_name_map[ctname]['ShopClass'],
                'pt':tdata_name_map[ctname]['pt'],
                'iszd':tdata_name_map[ctname]['iszd'],
                'FuncName':Task_Fuc_dict.get(ctid),
                'isMulti':tdata_name_map[ctname]['isMulti'],
                'timing':tdata_name_map[ctname]['timing'],
                'gtName':tdata_name_map[ctname]['gtName'],
                'position':tdata_name_map[ctname]['position'],
                'mutilTiming':tdata_name_map[ctname]['mutilTiming']
            }
            zds=list(pdata.keys())
            paras=list(pdata.values())
            aff=tms.merge_into('task',zds,paras,['tName'])

            print(f'任务ID:{ctid},任务名:《{ctname}》,上传状态:{aff}')

        else:
            print(f'任务ID:{ctid},任务名:《{ctname}》,没找到映射')
        
def upload_1688acc():
    ppp=get_group_list('1688买家号 - 采购用')
    blist=ppp['blist']

    for binfo in blist:

        bid=binfo['profile_id']
        gid=binfo['group_id']
        gname=binfo['group_name']
        bname=binfo['name']
        if bname=='开发测试':
            print('跳过')
            continue
        ProxyIP=None
        if binfo['user_proxy_config'].get('proxy_host'):
            ipstr=binfo['user_proxy_config']['proxy_host']
            port=binfo['user_proxy_config']['proxy_host']
            proxy_type=binfo['user_proxy_config']['proxy_type']
            porxy_uid=binfo['user_proxy_config']['proxy_user']
            proxy_pwd=binfo['user_proxy_config']['proxy_password']
            ProxyIP=f'{proxy_type}://{porxy_uid}:{proxy_pwd}@{ipstr}:{port}',
        
        pdict={
            'BrowserID':bid,
            'DpName':bname,
            'GroupID':gid,
            'GroupName':gname,
            'ProxyIP':ProxyIP,
            'is_cj_order':1

        }

        zds=list(pdict.keys())
        paras=list(pdict.values())

        aff=tms.merge_into('S1688Account',zds,paras,['BrowserID'],True)

        print(f'存入浏览器:{bid},信息状态:{aff}')

def upload_cjkw():

    '''上传采集关键词'''

    wb=openpyxl.load_workbook('1688类目关键词.xlsx')
    ws=wb[wb.sheetnames[0]]

    max_r=ws.max_row
    
    for gj in ['shopee印尼','shopee泰国']:
        suc=0
        for r in  range(1,max_r+1):
            cval=ws.cell(r,1).value.strip()
            kdata={
                'keyword':cval,
                'emarket':gj,
                'keyword_type':'广泛匹配关键词',
                'gender':5
            }
            zds=list(kdata.keys())
            paras=list(kdata.values())
            aff=tms.merge_into('keyword_1688',zds,paras,['keyword','emarket'],True)
            suc+=aff
            print(f'第 {r} 个,{gj},关键词《{cval}》,上传状态:{aff}')
        print(f'共 {max_r} 个词,{gj}成功上传 {suc} 个')

async def ck_asd_api(bid,api_type=1):

    if api_type==1:

        url=f'{ADSPower_API_URL}/api/v2/browser-profile/active'
        params={
            'profile_id':bid
        }
    elif api_type==2:
        url=f'{ADSPower_API_URL}/api/v2/browser-profile/start'
        data={
            'profile_id':bid
        }
    elif api_type==3:
        url=f'{ADSPower_API_URL}/api/v2/browser-profile/stop'
        data={
            'profile_id':bid
        }
    try:
        
        if api_type==1:
            res=requests.get(url,params=params,timeout=60)
        else:
            res=requests.post(url,json=data,timeout=60)
        
        print(f'请求状态码:{res.status_code}')
        json_data=res.json()
        print(f'请求结果:{json_data}')

        if api_type==2:
            playwright = await async_playwright().start()
            ws_url = json_data['data']['ws']['puppeteer']
            try:
                browser = await playwright.chromium.connect_over_cdp(ws_url)
                ctx=browser.contexts[0]
                page=await ctx.new_page()
                
            except Exception as e:
                traceback.print_exc()
                print(f'接管浏览器错误 => {e}')
            finally:
                print(f'等待5秒关闭接管')
                await asyncio.sleep(5)
                await page.close()
                await ctx.close()
                await browser.close()
                await playwright.stop()
            
    
    except Exception as e:
        traceback.print_exc()
        print(f'接管{url},错误 => {e}')

def set_column_comments(jsdata_path):

    ss = os.path.basename(jsdata_path)  
    tb_name = os.path.splitext(ss)[0]
    with open(jsdata_path,'r',encoding='utf-8') as f:
        col_map=json.load(f)
    
    for en_name,cn_name in col_map.items():

        tms.add_column_comment(tb_name,en_name,cn_name)

# path_list=os.listdir('TABLEJSON')
# for path in path_list:
#     if path=='TABLE.json':
#         continue
#     sss=os.path.join('TABLEJSON',path)
#     set_column_comments(sss)